const express = require("express");
const router = express.Router();
const { Like, Course, User } = require("../models");
const { success, fail } = require("../utils/response");

// 查询点赞
router.get("/", async (req, res) => {
  const { pageNum, pageSize } = req.body;
  try {
    const conditions = getConditions(req);
    const { count, rows } = await Like.findAndCountAll(conditions);
    console.log("list==", rows);
    success(res, "获取成功", {
      list: rows,
      pageNum: pageNum,
      pageSize: pageSize,
      count,
    });
  } catch (error) {
    console.log(error);
    fail(res, "查询失败");
  }
});
function getConditions(req) {
  const { userId, courseId, pageNum = 1, pageSize = 10 } = req.body;
  const conditions = {
    where: {},
    offset: (pageNum - 1) * pageSize,
    limit: pageSize,
  };
  if (userId) {
    conditions.where.UserId = userId;
  }
  if (courseId) {
    conditions.where.CourseId = courseId;
  }
  return conditions;
}
// 新增点赞/取消点赞
router.post("/", async (req, res) => {
  const { userId, courseId } = req.body;
  try {
    const curlike = await Like.findOne({ 
      attributes: ['id', 'CourseId'],
      where: { UserId: userId, CourseId: courseId } 
    });
    // 已点赞，则取消点赞
    if (curlike) {
      await Like.destroy({ where: { id: curlike.id } });
      const deleteNum = await Course.decrement({ likeCount: 1 }, { where: { id: courseId } });
      success(res, "取消点赞成功", 0);
    } else {
      // 未点赞，则点赞
      const like = await Like.create({
        UserId: userId,
        CourseId: courseId,
      });
      const incrementLikeNum = await Course.increment(
        { likeCount: 1 },
        { where: { id: courseId } }
      );
      success(res, "点赞成功", 1);
    }
  } catch (error) {
    console.log(error);
    fail(res, "点赞失败");
  }
});

module.exports = router;
